package com.xongxong.admin.web.controller;


import com.google.common.cache.Cache;
import com.xongxong.admin.common.constants.Constants;
import com.xongxong.admin.common.response.Response;
import com.xongxong.admin.service.UserInfoService;
import com.xongxong.admin.utils.EncryptionDecryption;
import com.xongxong.admin.web.controller.dto.login.loginDto;
import com.xongxong.domain.req.loginReq;
import com.xongxong.domain.vo.userVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author dxx
 * @since 2024-12-01
 */
@Slf4j
@RestController
@RequestMapping("/user-info")
public class LoginController {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private Cache<String, userVo> userInfoCache;

    @Resource
    private Cache<String, String> codeToken;
    @PostMapping("/login")
    public Response<Object> login(@RequestBody loginDto loginDto, HttpServletRequest request) {
        String codeValue = loginDto.getCode();
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        String codeKey = request.getHeader(Constants.CachStatusEnum.COKE_KEY.getDesc());
        log.info("接收到参数中,验证码为:{},账号为：{},密码为:{}", codeValue, username, password);
        String passwordSha256 = EncryptionDecryption.encrypt(password);
        log.info("passwordSha256:{}", passwordSha256);
        userVo user = userInfoService.login(loginReq.builder().codeKey(codeKey).codeValue(codeValue).username(username).password(passwordSha256).build());
        userInfoCache.put(Constants.CachStatusEnum.EASY_ADMIN_TOKEN.getDesc(),user);
        // 删除验证码缓存
        codeToken.invalidate(codeKey);
        return Response.ok();
    }

    @PostMapping("/logout")
    public Response<Object> logout() {
        String logout = userInfoService.logout();
        return Response.ok(logout);
    }
}
